package com.pureland.ucc.config.oauth;

import com.pureland.security.exceptions.InvalidException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import java.util.Map;

/**
 * @projectName: pureland_cloud
 * @className: com.pureland.ucc.config.oauth.AbstractCustomTokenGranter
 * @description: 自定义抽象令牌授予者
 * @author: tong.li
 * @createTime: 2020/11/19 15:31
 * @version: v1.0
 * @copyright: 版权所有 李彤 © 2020
 */
public abstract class AbstractCustomTokenGranter extends AbstractTokenGranter {

    private final OAuth2RequestFactory requestFactory;

    public AbstractCustomTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.requestFactory = requestFactory;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws InvalidException  {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        UserDetails user = getUser(parameters);
        if (user == null) {
            throw new InvalidGrantException("无法获取用户信息");
        }
        OAuth2Request oAuth2Request = this.requestFactory.createOAuth2Request(client, tokenRequest);
        PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(user, null, user.getAuthorities());
        authentication.setDetails(user);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        return oAuth2Authentication;
    }

    protected abstract UserDetails getUser(Map<String, String> parameters) throws  InvalidException;
}
